﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PSLib.CodeFormating.Formatters;
using PSLib.CodeFormating.Lexems;

namespace LuaCodeStyler
{
	public partial class TemplateLexemEditForm : Form
	{
		public TemplateLexemEditForm()
		{
			InitializeComponent();
			foreach (LexemType item in Enum.GetValues(typeof(LexemType)))
			{
				if (item != LexemType.None) comboBox1.Items.Add(item);
			}

			comboBox1.SelectedIndex = 0;
		}

		private void buttonOk_Click(object sender, EventArgs e)
		{
			this.DialogResult = DialogResult.OK;
			Close();
		}

		private void buttonCancel_Click(object sender, EventArgs e)
		{
			Close();
		}
		
		public LexemConfiguration LexemConfiguration
		{
			get 
			{
				LexemType type = (LexemType)comboBox1.SelectedItem;
				LexemConfiguration result = new LexemConfiguration(type);
				result.Name = textBoxName.Text;
				result.Description = textBoxDescription.Text;
				result.Prefix = textBoxPrefix.Text;
				result.Postfix = textBoxPostfix.Text;

				foreach (DataGridViewRow item in dataGridView1.Rows)
				{
					if (item.Cells[0].Value == null && item.Cells[1].Value == null) continue;
					string key = string.Empty;
					string value = string.Empty;
					if (item.Cells[0].Value != null) key = item.Cells[0].Value.ToString();
					if (item.Cells[1].Value != null) value = item.Cells[1].Value.ToString();

					if (!result.ReplacementCollection.ContainsKey(key))
					{
						string formattedValue = string.Empty;
						while(!string.IsNullOrEmpty(value))
						{
							char symbol = value[0];
							if (value.StartsWith("{\\n}"))
							{
								symbol = '\n';
								value = value.Substring(3);
							}
							if (value.StartsWith("{\\r}"))
							{
								symbol = '\r';
								value = value.Substring(3);
							}
							if (value.StartsWith("{\\t}"))
							{
								symbol = '\t';
								value = value.Substring(3);
							}
							value = value.Substring(1);
							formattedValue += symbol;
						}

						result.ReplacementCollection.Add(key, formattedValue);
					}
				}
				
				return result;
			}
			set 
			{ 
				if(value == null) return;
				comboBox1.SelectedItem = value.LexemType;
				textBoxName.Text = value.Name;
				textBoxDescription.Text = value.Description;
				textBoxPrefix.Text = value.Prefix;
				textBoxPostfix.Text = value.Postfix;
				foreach (var item in value.ReplacementCollection)
					dataGridView1.Rows.Add(item.Key,item.Value);
			}
		}
	}
}
